#!/usr/bin/env python
# -*- coding:utf8 -*-
"""
Author : mafei
@Date   : 2019/12/02

"""
import errno
import fcntl
import hashlib
import os

ROOT_DIR = u'/data/lock_files'

_global_fds = {}


# 生成文件名
def gen_lock_filename(info):
    return hashlib.md5(info).hexdigest()


# 在指定文件上成功获得锁返回True
def lock_file(f):
    if not os.path.isdir(ROOT_DIR):
        os.makedirs(ROOT_DIR)
    global _global_fds
    if os.path.isabs(f):
        abs_file = f
    else:
        abs_file = os.path.join(ROOT_DIR, f)
    if abs_file in _global_fds:
        return False
    _global_fds[abs_file] = open(abs_file, u'w')
    try:
        fcntl.lockf(_global_fds[abs_file], fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError as e:
        if e.errno in (errno.EACCES, errno.EAGAIN):
            return False
        return False
    except Exception as e2:
        return False
    else:
        return True


# 释放文件锁不需要关注成功或者失败
def release_file(f):
    global _global_fds
    if os.path.isabs(f):
        abs_file = f
    else:
        abs_file = os.path.join(ROOT_DIR, f)
    fd = open(abs_file, 'w')
    try:
        fcntl.lockf(fd, fcntl.LOCK_UN)
        del _global_fds[abs_file]
    except KeyError as ke:
        pass
    except Exception as e:
        return
